package priv.jesse.mall.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import priv.jesse.mall.dao.AddressDao;
import priv.jesse.mall.dao.OrderDao;
import priv.jesse.mall.dao.ProductDao;
import priv.jesse.mall.dao.ShopcartDao;
import priv.jesse.mall.entity.*;
import priv.jesse.mall.service.ProductService;
import priv.jesse.mall.service.ShopCartService;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author hfb
 * @date 2017/11/21
 */
@Service
public class ShopCartServiceImpl implements ShopCartService {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private ShopcartDao shopcartDao;

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private OrderDao orderDao;

    /**
     * 加购物车
     * 将商品id保存到Session中List<Integer>中
     *
     * @param productId
     * @param request
     */
    @Override
    public void addCart(int productId,HttpServletRequest request) throws Exception {
        User loginUser = (User) request.getSession().getAttribute("user");
        if (loginUser == null)
            throw new Exception("未登录！请重新登录");
        List<Integer> productIds = (List<Integer>) request.getSession().getAttribute(NAME_PREFIX + loginUser.getId());
        if (productIds == null) {
            productIds = new ArrayList<>();
            request.getSession().setAttribute(NAME_PREFIX + loginUser.getId(), productIds);
        }
        productIds.add(productId);
    }



/**
 * 加购物车
 * 将商品id保存到Session中List<Integer>中
 *
 * @param productId
 * @param request
 */
    @Override
    public void newaddCart(int productId,int prodCount,HttpServletRequest request) throws Exception {
        User loginUser = (User) request.getSession().getAttribute("user");
        if (loginUser == null) {
            throw new Exception("未登录！请重新登录");
        }
        productDao.addCart(loginUser.getId(),productId,prodCount);
    }

    /**
     * 加载购物车
     * 将商品id保存到Session中List<Integer>中
     * @param request
     */
    @Override
    public List<OrderItem> loadlistCart(HttpServletRequest request) throws Exception {
        User loginUser = (User) request.getSession().getAttribute("user");
        if (loginUser == null) {
            throw new Exception("未登录！请重新登录");
        }
        String urlprefix = request.getScheme() + "://"
                + request.getServerName() + ":"
                + request.getServerPort();
        //查询购物车表
        Integer id = loginUser.getId();
        List<Shopcart> shoplist=shopcartDao.loadlistCart(id);

        Map<Integer, OrderItem> productMap = new HashMap<>();
        List<OrderItem> orderItems = new ArrayList<>();
        if (shoplist == null){
            return new ArrayList<>();
        }
        // 遍历List中的商品id，每个商品Id对应一个OrderItem
        for (Shopcart Shopcart : shoplist) {
           // if (productMap.get(Shopcart.getProId()) == null) {
                Product product = productService.findById(Shopcart.getProId());
                String[] ss=product.getImage().split("&");
                if(ss[0].indexOf(urlprefix)<0){
                    String image=urlprefix.trim()+"/mall/admin/product/getImg.do?url="+ ss[0].replace("/","%2F").replace("\\","%2F");
                    product.setImage(image);
                }
                OrderItem orderItem = new OrderItem();
                orderItem.setId(Shopcart.getId());
                orderItem.setProduct(product);
                orderItem.setProductId(Shopcart.getProId());
                orderItem.setCount(Shopcart.getBuyCount());
                orderItem.setSubTotal(product.getShopPrice());
                orderItems.add(orderItem);
        }
        return orderItems;
    }

    @Override
    public Order payment(HttpServletRequest request,Integer shortid){
        String urlprefix = request.getScheme() + "://"
                + request.getServerName() + ":"
                + request.getServerPort();
        //查询订单
        Order order=orderDao.findById(shortid);
        if(order==null){
            return null;
        }
        List<OrderItem> orderItems = new ArrayList<>();
        String[] ids=order.getPhone().split(",");
        for(int i=0;i<ids.length;i++){
            Shopcart shopcart=shopcartDao.findById(Integer.parseInt(ids[i]));
            Product product = productService.findById(shopcart.getProId());
            String[] ss=product.getImage().split("&");
            if(ss[0].indexOf(urlprefix)<0){
                String image=urlprefix.trim()+"/mall/admin/product/getImg.do?url="+ ss[0].replace("/","%2F").replace("\\","%2F");
                product.setImage(image);
            }
            OrderItem orderItem = new OrderItem();
            orderItem.setId(shopcart.getId());
            orderItem.setProduct(product);
            orderItem.setProductId(shopcart.getProId());
            orderItem.setCount(shopcart.getBuyCount());
            orderItem.setSubTotal(product.getShopPrice());
            orderItems.add(orderItem);
            }
        order.setOrderItemList(orderItems);
        return order;
    }














    /**
     * 加载购物车数量
     * 将商品id保存到Session中List<Integer>中
     * @param request
     */
    @Override
    public int loadShopcount(HttpServletRequest request) throws Exception {
        User loginUser = (User) request.getSession().getAttribute("user");
        if (loginUser == null) {
            throw new Exception("未登录！请重新登录");
        }
        int i=productDao.loadShopcount(loginUser.getId());
        return i;
    }


    /**
     * 移除
     *
     * 移除session List中对应的商品Id
     *
     * @param productId
     * @param request
     */
    @Override
    public void remove(int productId, HttpServletRequest request) throws Exception {
        User loginUser = (User) request.getSession().getAttribute("user");
        if (loginUser == null)
            throw new Exception("未登录！请重新登录");
        List<Integer> productIds = (List<Integer>) request.getSession().getAttribute(NAME_PREFIX + loginUser.getId());
        Iterator<Integer> iterator = productIds.iterator();
        while (iterator.hasNext()) {
            if (productId == iterator.next()) {
                iterator.remove();
            }
        }
    }

    /**
     * 查看购物车
     *
     * 查询出session的List中所有的商品Id,并封装成List<OrderItem>返回
     *
     * @param request
     * @return
     */
    @Override
    public List<OrderItem> listCart(HttpServletRequest request) throws Exception {
        User loginUser = (User) request.getSession().getAttribute("user");
        if (loginUser == null)
            throw new Exception("未登录！请重新登录");
        List<Integer> productIds = (List<Integer>) request.getSession().getAttribute(NAME_PREFIX + loginUser.getId());
        // key: productId value:OrderItem
        Map<Integer, OrderItem> productMap = new HashMap<>();
        if (productIds == null){
            return new ArrayList<>();
        }
        // 遍历List中的商品id，每个商品Id对应一个OrderItem
        for (Integer productId : productIds) {
            if (productMap.get(productId) == null) {
                Product product = productService.findById(productId);
                OrderItem orderItem = new OrderItem();
                orderItem.setProduct(product);
                orderItem.setProductId(productId);
                orderItem.setCount(1);
                orderItem.setSubTotal(product.getShopPrice());
                productMap.put(productId, orderItem);
            } else {
                OrderItem orderItem = productMap.get(productId);
                int count = orderItem.getCount();
                orderItem.setCount(++count);
                Double subTotal = orderItem.getSubTotal();
                orderItem.setSubTotal(orderItem.getSubTotal()+subTotal);
                productMap.put(productId, orderItem);
            }
        }
        List<OrderItem> orderItems = new ArrayList<>(productMap.values());
        return orderItems;
    }






    @Override
    public int shortdelete(HttpServletRequest request,int shopcartid){
        shopcartDao.deleteById(shopcartid);
        return 1;
    }

    @Override
    public int updateshortcount(HttpServletRequest request,int cardId,int count){
        Shopcart cart=shopcartDao.findById(cardId);
        cart.setBuyCount(cart.getBuyCount()+count);
        shopcartDao.save(cart);
        return 1;
    }

    @Override
    public List<Address> loadeadress(int userid){
        return addressDao.getByUserId(userid);
    }

    @Override
    public Integer updateadress(HttpServletRequest request,String addressss)throws Exception{
        User loginUser = (User) request.getSession().getAttribute("user");
        if (loginUser == null){
            throw new Exception("未登录！请重新登录");
        }
        addressDao.deleteByUserId(loginUser.getId());
        String[] ads=addressss.split(",");
        for(int i=0;i<ads.length;i++){
            Address addres=new Address();
            addres.setUserId(loginUser.getId());
            addres.setAddress(ads[i]);
            addressDao.save(addres);
        }
        return 1;
    }

}
